package cn.xs.goods.dao.impl;



import java.util.List;

import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.xs.core.dao.impl.BaseDaoImpl;
import cn.xs.goods.dao.GoodDao;
import cn.xs.goods.entity.Good;


public class GoodDaoImpl extends BaseDaoImpl<Good> implements GoodDao {

	@Override
	public void save(Good entity) {
		try{
			String sql = "insert into t_good values(?,?,?,?,?,?,?);";
			Object[] params = {entity.getId(),entity.getName(),entity.getPrice(),entity.getDescription()
					,entity.getPlace(),entity.getImg(),entity.getCategory_id()};
			getQueryRunner().update(sql, params);
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public List<Good> findAllByCategory(String categoryid) {
		try{
			String sql = "select * from t_good where category_id = '"+categoryid+"';";
			return (List<Good>) getQueryRunner().query(sql, new BeanListHandler(Good.class));
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public List<Good> findAllByCategoryAndLimit(String categoryid, int pageNo,int pageSize) {
		try{
			String sql="select * from t_good where category_id = ?  limit ?,? ;";
			pageNo = pageNo*pageSize;
			Object[] params ={categoryid,pageNo,pageSize};
			return (List<Good>) getQueryRunner().query(sql, new BeanListHandler(Good.class), params);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}

	public long countGoodsByCategory(String categoryid) {
		try{
			String sql ="select count(*) from t_good where category_id = '"+categoryid+"';";
			return (Long) getQueryRunner().query(sql, new ScalarHandler());
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}

	public List<Good> findAllBySearchAndLimit(String searchName, int pageNo,int pageSize) {
		try{
			String sql="select * from t_good where name like '%"+searchName+"%'  limit ?,? ;";
			pageNo = pageNo*pageSize;
			Object[] params ={pageNo,pageSize};
			return (List<Good>) getQueryRunner().query(sql, new BeanListHandler(Good.class), params);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}
	
}
